<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>定义Java实体类为什么要实现Serializable？ | Xuan的博客</title><meta name="author" content="Xuan"><meta name="copyright" content="Xuan"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="定义Java实体类为什么要实现Serializable概述我们可以按着如下顺序进行思考  什么是序列化和反序列化？  什么是Serializable接口？  Java对象为什么要实现Serializable接口？  Java实现对象序列化的方式？  serialVersionUID是什么？  使用Serializable接口需要注意什么？  常见的序列化技术有哪些？   序列化和反序列化序列化：将">
<meta property="og:type" content="article">
<meta property="og:title" content="定义Java实体类为什么要实现Serializable？">
<meta property="og:url" content="http://leesmile.gitee.io/smile/2023/10/09/Java/Java%E7%90%86%E8%AE%BA/JavaSE%E6%A0%B8%E5%BF%83/%E5%AE%9A%E4%B9%89Java%E5%AE%9E%E4%BD%93%E7%B1%BB%E4%B8%BA%E4%BB%80%E4%B9%88%E8%A6%81%E5%AE%9E%E7%8E%B0Serializable%EF%BC%9F/index.html">
<meta property="og:site_name" content="Xuan的博客">
<meta property="og:description" content="定义Java实体类为什么要实现Serializable概述我们可以按着如下顺序进行思考  什么是序列化和反序列化？  什么是Serializable接口？  Java对象为什么要实现Serializable接口？  Java实现对象序列化的方式？  serialVersionUID是什么？  使用Serializable接口需要注意什么？  常见的序列化技术有哪些？   序列化和反序列化序列化：将">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/leesmile/image-host/raw/master/images/202310201611606.jpg">
<meta property="article:published_time" content="2023-10-09T01:53:46.000Z">
<meta property="article:modified_time" content="2023-10-09T01:53:46.000Z">
<meta property="article:author" content="Xuan">
<meta property="article:tag" content="Java">
<meta property="article:tag" content="序列化和反序列化">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/leesmile/image-host/raw/master/images/202310201611606.jpg"><link rel="shortcut icon" href="/smile/img/favicon.png"><link rel="canonical" href="http://leesmile.gitee.io/smile/2023/10/09/Java/Java%E7%90%86%E8%AE%BA/JavaSE%E6%A0%B8%E5%BF%83/%E5%AE%9A%E4%B9%89Java%E5%AE%9E%E4%BD%93%E7%B1%BB%E4%B8%BA%E4%BB%80%E4%B9%88%E8%A6%81%E5%AE%9E%E7%8E%B0Serializable%EF%BC%9F/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/smile/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/smile/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '定义Java实体类为什么要实现Serializable？',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-10-09 09:53:46'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/css/font.css" media="defer" onload="this.media='all'"><link rel="stylesheet" href="/css/custom.css" media="defer" onload="this.media='all'"><link rel="stylesheet" href="/css/whiteLine.css" media="defer" onload="this.media='all'"><link rel="stylesheet" href="/css/progress_bar.css" media="defer" onload="this.media='all'"><link rel="stylesheet" href="/css/cat.css"><link rel="stylesheet" href="/css/readPercent.css"><link rel="stylesheet" href="https://cdn1.tianli0.top/npm/element-ui@2.15.6/packages/theme-chalk/lib/index.css"><div id="myscoll"></div><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Zfour/Butterfly-double-row-display@1.00/cardlistpost.min.css"/>
<style>#recent-posts > .recent-post-item >.recent-post-info > .article-meta-wrap > .tags:before {content:"\A";
  white-space: pre;}#recent-posts > .recent-post-item >.recent-post-info > .article-meta-wrap > .tags > .article-meta__separator{display:none}</style>
<link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-footer-beautify@1.0.0/lib/runtime.css" media="print" onload="this.media='all'"><!-- hexo injector head_end end --><meta name="generator" content="Hexo 6.3.0"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://leesmile.gitee.io/smile/img/avatarImg.bmp" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/smile/archives/"><div class="headline">文章</div><div class="length-num">142</div></a><a href="/smile/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/smile/categories/"><div class="headline">分类</div><div class="length-num">32</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/smile/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/smile/archives/"><i class="fa-fw fas fa-archive"></i><span> 文章</span></a></div><div class="menus_item"><a class="site-page" href="/smile/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/smile/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gitee.com/leesmile/image-host/raw/master/images/202310201611606.jpg')"><nav id="nav"><span id="blog-info"><a href="/smile/" title="Xuan的博客"><span class="site-name">Xuan的博客</span></a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/smile/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/smile/archives/"><i class="fa-fw fas fa-archive"></i><span> 文章</span></a></div><div class="menus_item"><a class="site-page" href="/smile/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/smile/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div><div id="nav-right"><a class="meihua faa-parent animated-hover" onclick="toggleWinbox()" title="美化设置-自定义你的风格" id="meihua-button"><svg class="faa-tada icon" style="height:26px;width:26px;fill:currentColor;position:relative;top:8px" aria-hidden="true"><use xlink:href="#icon-tupian1"></use></svg></a><a class="sun_moon faa-parent animated-hover" onclick="switchNightMode()" title="浅色和深色模式转换" id="nightmode-button"><svg class="faa-tada" style="height:25px;width:25px;fill:currentColor;position:relative;top:7px" viewBox="0 0 1024 1024"><use id="modeicon" xlink:href="#icon-moon"></use></svg></a></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">定义Java实体类为什么要实现Serializable？</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-10-09T01:53:46.000Z" title="发表于 2023-10-09 09:53:46">2023-10-09</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-10-09T01:53:46.000Z" title="更新于 2023-10-09 09:53:46">2023-10-09</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/smile/categories/Java/">Java</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="定义Java实体类为什么要实现Serializable？"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div><section class="main-hero-waves-area waves-area"><svg class="waves-svg" xmlns="http://www.w3.org/2000/svg" xlink="http://www.w3.org/1999/xlink" viewBox="0 24 150 28" preserveAspectRatio="none" shape-rendering="auto"><defs><path id="gentle-wave" d="M -160 44 c 30 0 58 -18 88 -18 s 58 18 88 18 s 58 -18 88 -18 s 58 18 88 18 v 44 h -352 Z"></path></defs><g class="parallax"><use href="#gentle-wave" x="48" y="0"></use><use href="#gentle-wave" x="48" y="3"></use><use href="#gentle-wave" x="48" y="5"></use><use href="#gentle-wave" x="48" y="7"></use></g></svg></section><div id="post-top-cover"><img class="nolazyload" id="post-top-bg" src="background-image: url('https://gitee.com/leesmile/image-host/raw/master/images/202310201611606.jpg')"></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="定义Java实体类为什么要实现Serializable"><a href="#定义Java实体类为什么要实现Serializable" class="headerlink" title="定义Java实体类为什么要实现Serializable"></a>定义Java实体类为什么要实现Serializable</h1><h2 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h2><p>我们可以按着如下顺序进行思考</p>
<ol>
<li><p>什么是序列化和反序列化？</p>
</li>
<li><p>什么是Serializable接口？</p>
</li>
<li><p>Java对象为什么要实现Serializable接口？</p>
</li>
<li><p>Java实现对象序列化的方式？</p>
</li>
<li><p>serialVersionUID是什么？</p>
</li>
<li><p>使用Serializable接口需要注意什么？</p>
</li>
<li><p>常见的序列化技术有哪些？</p>
</li>
</ol>
<h2 id="序列化和反序列化"><a href="#序列化和反序列化" class="headerlink" title="序列化和反序列化"></a>序列化和反序列化</h2><p>序列化：将对象转化为字节序列（对象 -&gt; 可存储或传输的形式）</p>
<p>反序列化：将字节序列转化为对象 (可存储或传输的形式 -&gt; 对象)</p>
<h2 id="对象序列化的两种作用"><a href="#对象序列化的两种作用" class="headerlink" title="对象序列化的两种作用"></a>对象序列化的两种作用</h2><ol>
<li><p><strong>对象的持久化</strong></p>
<p>Java允许在内存中创建可复用的Java对象，但是这些对象只会JVM运行时存在，这些对象才会存在。但在现实的需求中，就可能存在要求在JVM停止运行后仍要保存该对象的情况，即需要<strong>将内存中的对象写入到硬盘中</strong>。</p>
</li>
<li><p><strong>网络传送对象</strong></p>
<p>可以通过序列化将主机A中的内存对象转化为字节序列传输到主机B中重新重构出该对象，即将值从一个应用程序域发送到另一个应用程序域，<strong>当你想用Sokcet在网络上传送对象时</strong>（如在分布式应用中），就需要实现序列化。</p>
</li>
</ol>
<h2 id="Serializable接口概述"><a href="#Serializable接口概述" class="headerlink" title="Serializable接口概述"></a><strong>Serializable接口概述</strong></h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//Serializable.java源码</span></span><br><span class="line"><span class="keyword">package</span> java.io;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">interface</span> <span class="title class_">Serializable</span> &#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Serializable中文翻译：序列化；可串行化；可序列化</p>
<p>我们可以看出，<code>Serializable</code>只是一个空接口，没有具体的内容，只是简单的<strong>标记</strong>该类可实例化。</p>
<p><strong>Serializable作用：标记该类可被序列化</strong></p>
<h2 id="Java实现序列化底层原理"><a href="#Java实现序列化底层原理" class="headerlink" title="Java实现序列化底层原理"></a>Java实现序列化底层原理</h2><p>序列化实现：</p>
<ol>
<li><p>Make a FileOutputStream</p>
<p><code>FileOutputStream fs = new FileOutputStream(&quot;foo.ser&quot;);</code></p>
</li>
<li><p>Make a ObjectOutputStream</p>
<p><code>ObjectOutputStream os = new ObjectOutputStream(fs);</code></p>
</li>
<li><p>write the object（序列化）</p>
<p><code>os.writeObject(myObject);</code></p>
</li>
<li><p>close the ObjectOutputStream</p>
<p><code>os.close();</code></p>
</li>
</ol>
<p>反序列化实现顺序：</p>
<ol>
<li><p>Make a ObjectInputStream</p>
<p><code>ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(&quot;foo.ser&quot;));</code></p>
</li>
<li><p>read the object (反序列化)</p>
<p><code>UserPo userPo = (UserPo) objectInputStream.readObject();</code></p>
</li>
</ol>
<p>示例代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//序列化</span></span><br><span class="line"><span class="type">FileOutputStream</span> <span class="variable">fs</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">FileOutputStream</span>(<span class="string">&quot;foo.ser&quot;</span>);</span><br><span class="line"><span class="type">ObjectOutputStream</span> <span class="variable">os</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ObjectOutputStream</span>(fs);</span><br><span class="line">os.writeObject(<span class="keyword">new</span> <span class="title class_">UserPo</span>());</span><br><span class="line"></span><br><span class="line"><span class="comment">//反序列化</span></span><br><span class="line"><span class="type">ObjectInputStream</span> <span class="variable">objectInputStream</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ObjectInputStream</span>(<span class="keyword">new</span> <span class="title class_">FileInputStream</span>(<span class="string">&quot;foo.ser&quot;</span>));</span><br><span class="line"><span class="type">UserPo</span> <span class="variable">userPo</span> <span class="operator">=</span> (UserPo) objectInputStream.readObject();</span><br><span class="line">System.out.println(<span class="string">&quot;name=&quot;</span>+userPo.getName());</span><br><span class="line"></span><br><span class="line">os.close();</span><br></pre></td></tr></table></figure>



<h2 id="serialVersionUID作用"><a href="#serialVersionUID作用" class="headerlink" title="serialVersionUID作用"></a>serialVersionUID作用</h2><p>Java的序列化机制是<strong>通过判断类的serialVersionUID来验证版本一致性</strong>的。在进行反序列化时，JVM会把传来的字节流中的serialVersionUID与本地相应实体类的serialVersionUID进行比较，如果相同就认为是一致的，可以进行反序列化，否则就会出现序列化版本不一致的异常，即是<em>InvalidCastException</em>。</p>
<p>serialVersionUID的两种显示生成方式：</p>
<ol>
<li><p>默认的1L：</p>
<p><code>private static final long serialVersionUID = 1L;</code></p>
</li>
<li><p>根据类名、接口名、成员方法及属性等来生成一个64位的哈希字段：</p>
<p><code>private static final long serialVersionUID = xxxxL;</code></p>
</li>
</ol>
<p><strong>设置通过类名生成serialVersionUID的方法：</strong></p>
<ol>
<li><p>打开File -&gt; Settings -&gt; 搜索<code>Inspections</code> -&gt; 搜索<code>serialVersionUID</code> -&gt; 勾选该选项</p>
<p><img src="https://gitee.com/leesmile/image-host/raw/master/images/202310201618220.png" alt="1696848165608"></p>
</li>
<li><p>在对应的类下ALT + 左键即可看到生成<em>serialVersionUID</em>的提示语</p>
<p><img src="https://gitee.com/leesmile/image-host/raw/master/images/202310201618221.png" alt="定义2"></p>
</li>
<li><p>生成的效果如下</p>
</li>
</ol>
<p><img src="https://gitee.com/leesmile/image-host/raw/master/images/202310201618222.png" alt="image"></p>
<h2 id="使用Serializable注意事项"><a href="#使用Serializable注意事项" class="headerlink" title="使用Serializable注意事项"></a>使用Serializable注意事项</h2><ol>
<li><p><strong>静态变量序列化</strong></p>
<p>序列化时不保存静态变量，序列化只会保存对象的状态，而静态变量属于对象的状态，因此不会被保存</p>
</li>
<li><p><strong>序列化子类时如果父类没有标记则不会序列化</strong></p>
<p>子类实现了Serializable，父类没有实现Serializable接口的话，父类不会被序列化</p>
</li>
<li><p><strong>序列化类的成员变量为对象类型</strong></p>
<p>如果某个序列化类的成员变量是对象类型，则该对象类型的类必须实现序列化</p>
</li>
<li><p><strong>序列化的存储规则</strong></p>
<p>当写入文件为同一对象时，并不会再将对象的内容进行存储，而只是再次存储一份引用，反序列化时恢复引用关系</p>
</li>
<li><p><strong>使用<code>@Transient</code>注解可以避免某个属性被序列化</strong></p>
<p>一旦变量被transient修饰，变量将不再是对象持久化的一部分，该变量内容在序列化后无法获得访问。<br>transient关键字只能修饰变量，而不能修饰方法和类。注意，本地变量是不能被transient关键字修饰的。变量如果是用户自定义类变量，则该类需要实现Serializable接口。</p>
</li>
<li><p><strong>深克隆（deep copy）</strong></p>
<p>序列化可用于创建对象的深复制，深复制是指创建一个新对象，并复制原始对象的所有状态，包括其包含的所有其他对象。</p>
</li>
</ol>
<h2 id="常见的序列化技术"><a href="#常见的序列化技术" class="headerlink" title="常见的序列化技术"></a>常见的序列化技术</h2><p>JDK Serializable、FST、Kryo、Protobuf、Thrift、Hession和Avro等</p>
<blockquote>
<p>可参考该文章：<a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/367131687">几种Java常用序列化框架的选型与对比</a></p>
</blockquote>
<p><em>参考文章：</em></p>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://developer.aliyun.com/article/650466">https://developer.aliyun.com/article/650466</a></p>
<p><a target="_blank" rel="noopener" href="https://juejin.cn/post/7138013263526101029">https://juejin.cn/post/7138013263526101029</a></p>
<p><a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/340258358">https://zhuanlan.zhihu.com/p/340258358</a></p>
<p><a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/235394296">https://zhuanlan.zhihu.com/p/235394296</a></p>
</blockquote>
</article><div class="post-copyright"><div class="post-copyright__title"><span class="post-copyright-info"><h>定义Java实体类为什么要实现Serializable？</h></span></div><div class="post-copyright__type"><span class="post-copyright-info"><a href="http://leesmile.gitee.io/smile/2023/10/09/Java/Java%E7%90%86%E8%AE%BA/JavaSE%E6%A0%B8%E5%BF%83/%E5%AE%9A%E4%B9%89Java%E5%AE%9E%E4%BD%93%E7%B1%BB%E4%B8%BA%E4%BB%80%E4%B9%88%E8%A6%81%E5%AE%9E%E7%8E%B0Serializable%EF%BC%9F/">http://leesmile.gitee.io/smile/2023/10/09/Java/Java理论/JavaSE核心/定义Java实体类为什么要实现Serializable？/</a></span></div><div class="post-copyright-m"><div class="post-copyright-m-info"><div class="post-copyright-a"><h>作者</h><div class="post-copyright-cc-info"><h>Xuan</h></div></div><div class="post-copyright-c"><h>发布于</h><div class="post-copyright-cc-info"><h>2023-10-09</h></div></div><div class="post-copyright-u"><h>更新于</h><div class="post-copyright-cc-info"><h>2023-10-09</h></div></div><div class="post-copyright-c"><h>许可协议</h><div class="post-copyright-cc-info"><a class="icon" rel="noopener" target="_blank" title="Creative Commons" href="https://creativecommons.org/"><i class="fab fa-creative-commons"></i></a><a rel="noopener" target="_blank" title="CC BY-NC-SA 4.0" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a></div></div></div></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/smile/tags/Java/">Java</a><a class="post-meta__tags" href="/smile/tags/%E5%BA%8F%E5%88%97%E5%8C%96%E5%92%8C%E5%8F%8D%E5%BA%8F%E5%88%97%E5%8C%96/">序列化和反序列化</a></div><div class="post_share"><div class="social-share" data-image="https://gitee.com/leesmile/image-host/raw/master/images/202310201611606.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/smile/2023/10/09/Java/VO%EF%BC%8CBO%EF%BC%8CPO%EF%BC%8CDO%EF%BC%8CDTO%E7%9A%84%E5%8C%BA%E5%88%AB/" title="VO，BO，PO，DO，DTO的区别"><img class="cover" src="https://gitee.com/leesmile/image-host/raw/master/images/202310201611606.jpg" onerror="onerror=null;src='/smile/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">VO，BO，PO，DO，DTO的区别</div></div></a></div><div class="next-post pull-right"><a href="/smile/2023/10/08/Java/IDEA%E7%9A%84TODO%E7%94%A8%E6%B3%95/" title="IDEA的TODO用法"><img class="cover" src="https://gitee.com/leesmile/image-host/raw/master/images/202310201611986.jpg" onerror="onerror=null;src='/smile/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">IDEA的TODO用法</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/smile/2023/10/09/Java/%E5%AE%9A%E4%B9%89Java%E5%AE%9E%E4%BD%93%E7%B1%BB%E4%B8%BA%E4%BB%80%E4%B9%88%E8%A6%81%E5%AE%9E%E7%8E%B0Serializable%EF%BC%9F/" title="定义Java实体类为什么要实现Serializable？"><img class="cover" src="https://gitee.com/leesmile/image-host/raw/master/images/202310201611606.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-10-09</div><div class="title">定义Java实体类为什么要实现Serializable？</div></div></a></div><div><a href="/smile/2023/06/09/Java/DbUtil/" title="DbUtil"><img class="cover" src="https://gitee.com/leesmile/image-host/raw/master/images/202310201611606.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-06-09</div><div class="title">DbUtil</div></div></a></div><div><a href="/smile/2023/10/08/Java/IDEA%E7%9A%84TODO%E7%94%A8%E6%B3%95/" title="IDEA的TODO用法"><img class="cover" src="https://gitee.com/leesmile/image-host/raw/master/images/202310201611986.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-10-08</div><div class="title">IDEA的TODO用法</div></div></a></div><div><a href="/smile/2023/06/09/Java/JDBC/" title="JDBC"><img class="cover" src="https://gitee.com/leesmile/image-host/raw/master/images/202310201611606.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-06-09</div><div class="title">JDBC</div></div></a></div><div><a href="/smile/2024/01/02/Java/Java%E5%B9%B3%E5%8F%B0%E7%9A%84%E7%89%B9%E6%80%A7/" title="Java平台的特性"><img class="cover" src="https://gitee.com/leesmile/image-host/raw/master/images/202310201611606.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2024-01-02</div><div class="title">Java平台的特性</div></div></a></div><div><a href="/smile/2023/10/09/Java/VO%EF%BC%8CBO%EF%BC%8CPO%EF%BC%8CDO%EF%BC%8CDTO%E7%9A%84%E5%8C%BA%E5%88%AB/" title="VO，BO，PO，DO，DTO的区别"><img class="cover" src="https://gitee.com/leesmile/image-host/raw/master/images/202310201611606.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-10-09</div><div class="title">VO，BO，PO，DO，DTO的区别</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="author_top is-center"><div class="avatar-img"><img src="https://leesmile.gitee.io/smile/img/avatarImg.bmp" onerror="this.onerror=null;this.src='/smile/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Xuan</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/smile/archives/"><div class="headline">文章</div><div class="length-num">142</div></a><a href="/smile/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/smile/categories/"><div class="headline">分类</div><div class="length-num">32</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%AE%9A%E4%B9%89Java%E5%AE%9E%E4%BD%93%E7%B1%BB%E4%B8%BA%E4%BB%80%E4%B9%88%E8%A6%81%E5%AE%9E%E7%8E%B0Serializable"><span class="toc-number">1.</span> <span class="toc-text">定义Java实体类为什么要实现Serializable</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A6%82%E8%BF%B0"><span class="toc-number">1.1.</span> <span class="toc-text">概述</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%BA%8F%E5%88%97%E5%8C%96%E5%92%8C%E5%8F%8D%E5%BA%8F%E5%88%97%E5%8C%96"><span class="toc-number">1.2.</span> <span class="toc-text">序列化和反序列化</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AF%B9%E8%B1%A1%E5%BA%8F%E5%88%97%E5%8C%96%E7%9A%84%E4%B8%A4%E7%A7%8D%E4%BD%9C%E7%94%A8"><span class="toc-number">1.3.</span> <span class="toc-text">对象序列化的两种作用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Serializable%E6%8E%A5%E5%8F%A3%E6%A6%82%E8%BF%B0"><span class="toc-number">1.4.</span> <span class="toc-text">Serializable接口概述</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Java%E5%AE%9E%E7%8E%B0%E5%BA%8F%E5%88%97%E5%8C%96%E5%BA%95%E5%B1%82%E5%8E%9F%E7%90%86"><span class="toc-number">1.5.</span> <span class="toc-text">Java实现序列化底层原理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#serialVersionUID%E4%BD%9C%E7%94%A8"><span class="toc-number">1.6.</span> <span class="toc-text">serialVersionUID作用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8Serializable%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9"><span class="toc-number">1.7.</span> <span class="toc-text">使用Serializable注意事项</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B8%B8%E8%A7%81%E7%9A%84%E5%BA%8F%E5%88%97%E5%8C%96%E6%8A%80%E6%9C%AF"><span class="toc-number">1.8.</span> <span class="toc-text">常见的序列化技术</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/smile/2024/04/08/%E4%B8%8D%E5%90%8C%E8%A7%92%E5%BA%A6%E5%87%BA%E5%8F%91%E5%8E%BB%E9%9C%80%E6%B1%82%E6%B2%9F%E9%80%9A%E9%97%AE%E9%A2%98/" title="不同角度出发去需求沟通问题"><img src="https://gitee.com/leesmile/image-host/raw/master/images/202310271509358.jpg" onerror="this.onerror=null;this.src='/smile/img/404.jpg'" alt="不同角度出发去需求沟通问题"/></a><div class="content"><a class="title" href="/smile/2024/04/08/%E4%B8%8D%E5%90%8C%E8%A7%92%E5%BA%A6%E5%87%BA%E5%8F%91%E5%8E%BB%E9%9C%80%E6%B1%82%E6%B2%9F%E9%80%9A%E9%97%AE%E9%A2%98/" title="不同角度出发去需求沟通问题">不同角度出发去需求沟通问题</a><time datetime="2024-04-08T07:55:46.000Z" title="发表于 2024-04-08 15:55:46">2024-04-08</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/smile/2024/04/01/%E4%BA%A7%E5%93%81%E5%95%86%E4%B8%9A%E8%AE%A1%E5%88%92%E6%96%B9%E5%90%91%E6%80%9D%E8%80%83/" title="产品商业计划方向思考"><img src="https://gitee.com/leesmile/image-host/raw/master/images/202310271509358.jpg" onerror="this.onerror=null;this.src='/smile/img/404.jpg'" alt="产品商业计划方向思考"/></a><div class="content"><a class="title" href="/smile/2024/04/01/%E4%BA%A7%E5%93%81%E5%95%86%E4%B8%9A%E8%AE%A1%E5%88%92%E6%96%B9%E5%90%91%E6%80%9D%E8%80%83/" title="产品商业计划方向思考">产品商业计划方向思考</a><time datetime="2024-04-01T07:55:46.000Z" title="发表于 2024-04-01 15:55:46">2024-04-01</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/smile/2024/03/28/%E5%85%AC%E5%8F%B8%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95%E8%90%BD%E5%9C%B0%E7%9A%84%E9%9A%BE%E7%82%B9/" title="公司自动化测试落地的难点"><img src="https://gitee.com/leesmile/image-host/raw/master/images/202310271509358.jpg" onerror="this.onerror=null;this.src='/smile/img/404.jpg'" alt="公司自动化测试落地的难点"/></a><div class="content"><a class="title" href="/smile/2024/03/28/%E5%85%AC%E5%8F%B8%E8%87%AA%E5%8A%A8%E5%8C%96%E6%B5%8B%E8%AF%95%E8%90%BD%E5%9C%B0%E7%9A%84%E9%9A%BE%E7%82%B9/" title="公司自动化测试落地的难点">公司自动化测试落地的难点</a><time datetime="2024-03-28T07:55:46.000Z" title="发表于 2024-03-28 15:55:46">2024-03-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/smile/2024/03/22/%E5%BC%82%E6%AD%A5%E4%BB%BB%E5%8A%A1%E7%9A%84%E5%85%B3%E9%94%AE%E5%9C%A8%E4%BA%A4%E4%BA%92%E8%AE%BE%E8%AE%A1/" title="异步任务的体验关键在交互设计"><img src="https://gitee.com/leesmile/image-host/raw/master/images/202310271509358.jpg" onerror="this.onerror=null;this.src='/smile/img/404.jpg'" alt="异步任务的体验关键在交互设计"/></a><div class="content"><a class="title" href="/smile/2024/03/22/%E5%BC%82%E6%AD%A5%E4%BB%BB%E5%8A%A1%E7%9A%84%E5%85%B3%E9%94%AE%E5%9C%A8%E4%BA%A4%E4%BA%92%E8%AE%BE%E8%AE%A1/" title="异步任务的体验关键在交互设计">异步任务的体验关键在交互设计</a><time datetime="2024-03-22T07:55:46.000Z" title="发表于 2024-03-22 15:55:46">2024-03-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/smile/2024/03/11/Git%E5%B7%A5%E4%BD%9C%E6%B5%81/" title="Git工作流"><img src="https://gitee.com/leesmile/image-host/raw/master/images/202310261354386.jpg" onerror="this.onerror=null;this.src='/smile/img/404.jpg'" alt="Git工作流"/></a><div class="content"><a class="title" href="/smile/2024/03/11/Git%E5%B7%A5%E4%BD%9C%E6%B5%81/" title="Git工作流">Git工作流</a><time datetime="2024-03-11T07:55:46.000Z" title="发表于 2024-03-11 15:55:46">2024-03-11</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2024 By Xuan</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i><span id="percent">0<span>%</span></span></button><button id="go-down" type="button" title="直达底部" onclick="btf.scrollToDest(document.body.scrollHeight, 500)"><i class="fas fa-arrow-down"></i></button></div></div><div><script src="/smile/js/utils.js"></script><script src="/smile/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><div class="js-pjax"></div><script async src="https://cdn1.tianli0.top/npm/vue@2.6.14/dist/vue.min.js"></script><script async src="https://cdn1.tianli0.top/npm/element-ui@2.15.6/lib/index.js"></script><script defer src="/js/cursor.js"></script><script async src="//npm.elemecdn.com/pace-js@1.2.4/pace.min.js"></script><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script><script defer data-pjax src="/js/cat.js"></script><script defer data-pjax src="/js/readPercent.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><!-- hexo injector body_end start --> <script data-pjax>if(document.getElementById('recent-posts') && (location.pathname ==='/'|| '/' ==='all')){
    var parent = document.getElementById('recent-posts');
    var child = '<div class="recent-post-item" style="width:100%;height: auto"><div id="catalog_magnet"><a class="magnet_link_more"  href="http://leesmile.gitee.io/smile/categories" style="flex:1;text-align: center;margin-bottom: 10px;">查看更多...</a></div></div>';
    console.log('已挂载magnet')
    parent.insertAdjacentHTML("afterbegin",child)}
     </script><style>#catalog_magnet{flex-wrap: wrap;display: flex;width:100%;justify-content:space-between;padding: 10px 10px 0 10px;align-content: flex-start;}.magnet_item{flex-basis: calc(50% - 5px);background: #87CEFA;margin-bottom: 10px;border-radius: 8px;transition: all 0.2s ease-in-out;}.magnet_item:hover{background: #00FFFF}.magnet_link_more{color:#555}.magnet_link{color:black}.magnet_link:hover{color:white}@media screen and (max-width: 600px) {.magnet_item {flex-basis: 100%;}}.magnet_link_context{display:flex;padding: 10px;font-size:16px;transition: all 0.2s ease-in-out;}.magnet_link_context:hover{padding: 10px 20px;}</style>
    <style></style><script data-pjax>
  function butterfly_footer_beautify_injector_config(){
    var parent_div_git = document.getElementById('footer-wrap');
    var item_html = '<div id="workboard"></div><p id="ghbdages"><a class="github-badge" target="_blank" href="https://hexo.io/" style="margin-inline:5px" data-title="博客框架为Hexo_v6.2.0" title=""><img src="https://img.shields.io/badge/Frame-Hexo-blue?style=flat&amp;logo=hexo" alt=""/></a><a class="github-badge" target="_blank" href="https://butterfly.js.org/" style="margin-inline:5px" data-title="主题版本Butterfly_v4.3.1" title=""><img src="https://img.shields.io/badge/Theme-Butterfly-6513df?style=flat&amp;logo=bitdefender" alt=""/></a><a class="github-badge" target="_blank" href="https://gitee.com/" style="margin-inline:5px" data-title="本站项目由Gitee托管" title=""><img src="https://img.shields.io/badge/Source-Github-d021d6?style=flat&amp;logo=GitHub" alt=""/></a><a class="github-badge" target="_blank" href="http://creativecommons.org/licenses/by-nc-sa/4.0/" style="margin-inline:5px" data-title="本站采用知识共享署名-非商业性使用-相同方式共享4.0国际许可协议进行许可" title=""><img src="https://img.shields.io/badge/Copyright-BY--NC--SA%204.0-d42328?style=flat&amp;logo=Claris" alt=""/></a></p>';
    console.log('已挂载butterfly_footer_beautify')
    parent_div_git.insertAdjacentHTML("beforeend",item_html)
    }
  var elist = 'null'.split(',');
  var cpage = location.pathname;
  var epage = 'all';
  var flag = 0;

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_footer_beautify_injector_config();
  }
  else if (epage === cpage){
    butterfly_footer_beautify_injector_config();
  }
  </script><script async src="https://npm.elemecdn.com/hexo-butterfly-footer-beautify@1.0.0/lib/runtime.js"></script><!-- hexo injector body_end end --></body></html>